﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Reflection;
using System.Net;

/// <summary>
/// Summary description for ThumNail
/// </summary>
public class ThumNail
{
    //public static string Url = System.Configuration.ConfigurationManager.AppSettings["Url"].ToString(); 

    public ThumNail()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region 字符串长度截取
    /// <summary>
    /// 字符串长度截取
    /// </summary>
    /// <param name="s"></param>
    /// <param name="l"></param>
    /// <returns></returns>
    public static string subStr(string s, int l)
    {
        if (s.Length > l)
        {
            return s.Substring(0, l);
        }
        return s;
    }
    #endregion

    #region 生成缩略图
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="orginalImagePat">原图片地址</param>
    /// <param name="thumNailPath">缩略图地址</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="model">生成缩略的模式</param>
    public static void MakeThumNail(string originalImagePath, string thumNailPath, int width, int height, string model)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
        int thumWidth = width;      //缩略图的宽度
        int thumHeight = height;    //缩略图的高度
        int x = 0;
        int y = 0;
        int originalWidth = originalImage.Width;    //原始图片的宽度
        int originalHeight = originalImage.Height;  //原始图片的高度
        switch (model)
        {
            case "HW":      //指定高宽缩放,可能变形
                break;
            case "W":       //指定宽度,高度按照比例缩放
                thumHeight = originalImage.Height * width / originalImage.Width;
                break;
            case "H":       //指定高度,宽度按照等比例缩放
                thumWidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut":
                if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                {
                    originalHeight = originalImage.Height;
                    originalWidth = originalImage.Height * thumWidth / thumHeight;
                    y = 0;
                    x = (originalImage.Width - originalWidth) / 2;
                }
                else
                {
                    originalWidth = originalImage.Width;
                    originalHeight = originalWidth * height / thumWidth;
                    x = 0;
                    y = (originalImage.Height - originalHeight) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);
        //新建一个画板
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);
        //设置高质量查值法
        graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //设置高质量，低速度呈现平滑程度
        graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //清空画布并以透明背景色填充
        graphic.Clear(System.Drawing.Color.Transparent);
        //在指定位置并且按指定大小绘制原图片的指定部分
        graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);
        try
        {
            bitmap.Save(thumNailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex)
        {

            throw ex;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            graphic.Dispose();
        }
    }
    #endregion

    #region 在图片上添加文字水印
    /// <summary>
    /// 在图片上添加文字水印
    /// </summary>
    /// <param name="path">要添加水印的图片路径</param>
    /// <param name="syPath">生成的水印图片存放的位置</param>
    /// <param name="syWord">图片上显示文本</param>
    public static void AddWaterWord(string path, string syPath, string syWord)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(path);

        //新建一个画板
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(image);
        graphic.DrawImage(image, 0, 0, image.Width, image.Height);

        //设置字体
        System.Drawing.Font f = new System.Drawing.Font("Verdana", 30);

        //设置字体颜色
        System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Gray);

        graphic.DrawString(syWord, f, b, 20, 120);
        graphic.Dispose();

        //保存文字水印图片
        image.Save(syPath);
        image.Dispose();

    }
    #endregion

    #region 在图片上添加图片水印
    /// <summary>
    /// 在图片上添加图片水印
    /// </summary>
    /// <param name="path">原服务器上的图片路径</param>
    /// <param name="syPicPath">水印图片的路径</param>
    /// <param name="waterPicPath">生成的水印图片存放路径</param>
    public static void AddWaterPic(string path, string syPicPath, string waterPicPath)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(path);
        System.Drawing.Image waterImage = System.Drawing.Image.FromFile(syPicPath);
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(image);
        graphic.DrawImage(waterImage, new System.Drawing.Rectangle(image.Width - waterImage.Width, image.Height - waterImage.Height, waterImage.Width, waterImage.Height), 0, 0, waterImage.Width, waterImage.Height, System.Drawing.GraphicsUnit.Pixel);
        graphic.Dispose();

        image.Save(waterPicPath);
        image.Dispose();
    }
    #endregion

    #region MD5加密方法
    /// <summary>
    ///MD5加密方法 32位大写
    /// </summary>
    /// <returns></returns>
    public static string Upper32(string s)
    {
        s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
        return s.ToUpper();
    }
    /// <summary>
    ///MD5加密方法 32位小写
    /// </summary>
    /// <returns></returns>
    public static string Lower32(string s)
    {
        s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
        return s.ToLower();
    }
    /// <summary>
    /// MD5加密方法 16位大写
    /// </summary>
    /// <returns></returns>
    public static string Upper16(string s)
    {
        s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
        return s.ToUpper().Substring(8, 16);
    }
    /// <summary>
    ///MD5加密方法  16位小写
    /// </summary>
    /// <returns></returns>
    public static string Lower16(string s)
    {
        s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
        return s.ToLower().Substring(8, 16);
    }


    #endregion


    #region DataSet转换为实体类
    /// <summary>
    /// DataSet转换为实体类
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    /// <param name="p_DataSet">DataSet</param>
    /// <param name="p_TableIndex">待转换数据表索引</param>
    /// <returns>实体类</returns>
    private static T DataSetToT<T>(DataSet p_DataSet, int p_TableIndex)
    {
        if (p_DataSet == null || p_DataSet.Tables.Count < 0)
            return default(T);
        if (p_TableIndex > p_DataSet.Tables.Count - 1)
            return default(T);
        if (p_TableIndex < 0)
            p_TableIndex = 0;
        if (p_DataSet.Tables[p_TableIndex].Rows.Count <= 0)
            return default(T);

        DataTable p_Data = p_DataSet.Tables[p_TableIndex];
        // 返回值初始化
        IList<T> result = new List<T>();
        for (int j = 0; j < p_Data.Rows.Count; j++)
        {
            T _t = (T)Activator.CreateInstance(typeof(T));
            PropertyInfo[] propertys = _t.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                for (int i = 0; i < p_Data.Columns.Count; i++)
                {
                    // 属性与字段名称一致的进行赋值
                    if (pi.Name.ToLower().Equals(p_Data.Columns[i].ColumnName.ToLower()))
                    {
                        // 数据库NULL值单独处理
                        if (p_Data.Rows[j][i] != DBNull.Value)
                        {
                            pi.SetValue(_t, p_Data.Rows[j][i], null);
                        }
                        else
                        {
                            pi.SetValue(_t, null, null);
                        }
                        break;
                    }
                }
            }
            result.Add(_t);
        }
        return result[0];
    }

    #endregion

    #region   获取登陆的  IP
    /// <summary>
    /// 获取Ip
    /// </summary>
    /// <returns></returns>
    public static string GetIp()
    {
        string Ipstr = "";
        try
        {
            System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
            IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress curAdd in heserver.AddressList)
            {
                Ipstr = curAdd.ToString();
            }

        }
        catch (Exception)
        {
            Ipstr = "255.255.255.255";
        }
        return Ipstr;
    }

    /// <summary>
    /// 取远程用户IP地址 
    /// </summary>
    /// <param name="Request">当前页面的Request</param>
    /// <returns>返回ip</returns>
    public static string GetIp(HttpRequest Request)
    {
        string user_IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
        return user_IP;
    }
    /// <summary>
    /// 穿过代理服务器取远程用户真实IP地址
    /// </summary>
    /// <param name="Request">当前页面的Request</param>
    /// <returns>返回ip</returns>
    public static string GetIp_VPN(HttpRequest Request)
    {
        string user_IP = "";
        if (Request.ServerVariables["HTTP_VIA"] != null)
        {
            user_IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else
        {
            user_IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        return user_IP;
    }
    #endregion

    #region   获取主机名称
    /// <summary>
    /// 获取主机名称    返回如  www.myWeb.com  or   www.myWeb.com:8080  注意没有 http://
    /// </summary>
    /// <returns></returns>
    public static string GetHttpHost()
    {
        int Port = HttpContext.Current.Request.Url.Port;
        if (Port == 80)
        {
            return HttpContext.Current.Request.Url.Host;
        }
        else
        {
            return HttpContext.Current.Request.Url.Host + ":" + Port;
        }

    }
    #endregion

}
